﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data.SqlClient;
using System.Drawing;
using System.Web.Configuration;
using lcomixcore;

namespace comix.admininstration
{
    
    

    public partial class books : System.Web.UI.Page
    {
        public int selid;

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected override void  OnLoadComplete(EventArgs e)
        {
 	        base.OnLoadComplete(e);
            
          //  if (!IsPostBack)
          //  {
                if (ListView1.EditItem != null)
                {
                    Label l = (Label)ListView1.EditItem.Controls[1];
                    selid = Convert.ToInt32(l.Text);
                }
          //  }
        }

        private void SelectItem(DropDownList ddl, int value)
        {
            for (int i = 0; i < ddl.Items.Count; i++)
            {
                if (ddl.Items[i].Value == value.ToString())
                {
                    ddl.SelectedIndex = i;
                    break;
                }
            }
        }

        protected void ListView1_ItemInserting(object sender, ListViewInsertEventArgs e)
        {
            e.Values.Add("bok_ser_id", DropDownList1.SelectedValue);

         
        }

        protected void ListView1_ItemUpdating(object sender, ListViewUpdateEventArgs e)
        {
            e.NewValues.Add("bok_ser_id", DropDownList1.SelectedValue);
            DropDownList ddl = (DropDownList)ListView1.EditItem.FindControl("tiers_list");
            e.NewValues.Add("bok_ptr_id", ddl.SelectedValue);


        }



        protected void DeletePreview(object sender, CommandEventArgs e)
        {
            string dirname = Request.MapPath("../previews/" + e.CommandArgument.ToString());
            if (Directory.Exists(dirname))
                Directory.Delete(dirname, true);
            string dirname2 = Request.MapPath("../previews/wb" + e.CommandArgument.ToString());
            if (Directory.Exists(dirname2))
                Directory.Delete(dirname2, true);
        }

        protected void CreatePreview(object sender, CommandEventArgs e)
        {
            const int WW = 300;
            const int HH = 370;

            string dirname = Request.MapPath("../previews/"+e.CommandArgument.ToString());
            if (!Directory.Exists(dirname))
                Directory.CreateDirectory(dirname);
            string dirname2 = Request.MapPath("../previews/wb" + e.CommandArgument.ToString());
            if (!Directory.Exists(dirname2))
                Directory.CreateDirectory(dirname2);
            string bookpath = Request.MapPath("../books/" + e.CommandArgument.ToString() + ".cmk");
            if (File.Exists(bookpath))
            {
                lBook book = new lBook();
                book.Open(bookpath);
                lRbook rbook = book.Rbook;
                int h = 600;
                int w = rbook.Width * h / rbook.Height;
                System.Drawing.Size sz = new System.Drawing.Size(w, h);
                TextBox tb = (TextBox)ListView1.EditItem.FindControl("tbpages");
                char[] sep = { ' ' };
                string[] pgs = tb.Text.Split(sep, StringSplitOptions.RemoveEmptyEntries);
                foreach (string s in pgs)
                {
                    int pgno;
                    if (int.TryParse(s, out pgno))
                    {
                        lRpage pg = (lRpage)rbook.Pages[pgno - 1].getResolved();
                        System.Drawing.Bitmap b = pg.GetThumbnailOfPage(sz);
                        string impath = dirname + "/" + pgno.ToString() + ".jpg";
                        string impath2 = dirname2+"/"+pgno.ToString()+".jpg";
                        b.Save(impath, System.Drawing.Imaging.ImageFormat.Jpeg);

                        Bitmap b2 = new Bitmap(WW, HH);
                        Graphics g = Graphics.FromImage(b2);
                        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                        g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                        g.Clear(Color.Black);

                        Rectangle rsrc = new Rectangle(0, 0, b.Width, b.Height);
                        int hh = b.Height * WW / b.Width;
                        int ww = WW;
                        if (hh > HH)
                        {
                            hh = HH;
                            ww = b.Width * HH / b.Height;
                        }
                        Rectangle rdest = new Rectangle((WW - ww) / 2, (HH - hh) / 2, ww, hh);
                        g.DrawImage(b, rdest, rsrc, GraphicsUnit.Pixel);
                        g.Dispose();

                        b2.Save(impath2, System.Drawing.Imaging.ImageFormat.Jpeg);

                        b2.Dispose();
                        b.Dispose();
                    }
                }
            }
        }

   /*     protected void CreateSmallThumbnail(object sender, CommandEventArgs e)
        {
            string fn = Request.MapPath("../thumbs/small/" + e.CommandArgument.ToString() + ".jpg");
            string bookpath = Request.MapPath("../books/" + e.CommandArgument.ToString() + ".cmk");
            if (File.Exists(bookpath))
            {
                lBook book = new lBook();
                book.Open(bookpath);
                lRbook rbook = book.Rbook;
                int h = 130;
                int w = (int)((float)(rbook.Width * h) / rbook.Height);
                System.Drawing.Size sz = new System.Drawing.Size(w, h);
                lRpage pg = (lRpage)rbook.Pages[0].getResolved();
                System.Drawing.Bitmap b = pg.GetThumbnailOfPage(sz);
                b.Save(fn, System.Drawing.Imaging.ImageFormat.Jpeg);
                b.Dispose();
            }
        }

        protected void CreateLargeThumbnail(object sender, CommandEventArgs e)
        {
            string fn = Request.MapPath("../thumbs/large/" + e.CommandArgument.ToString() + ".jpg");
            string bookpath = Request.MapPath("../books/" + e.CommandArgument.ToString() + ".cmk");
            if (File.Exists(bookpath))
            {
                lBook book = new lBook();
                book.Open(bookpath);
                lRbook rbook = book.Rbook;
                int h = 220;
                int w = (int)((float)(rbook.Width * h) / rbook.Height);
                System.Drawing.Size sz = new System.Drawing.Size(w, h);
                lRpage pg = (lRpage)rbook.Pages[0].getResolved();
                System.Drawing.Bitmap b = pg.GetThumbnailOfPage(sz);
                b.Save(fn, System.Drawing.Imaging.ImageFormat.Jpeg);
                b.Dispose();
            }
        }*/

      /*  protected void UploadSample(object sender, CommandEventArgs e)
        {
            FileUpload fu = (FileUpload)ListView1.EditItem.FindControl("FileUploadSample");
            if (fu.HasFile)
            {
                string fn = Request.MapPath("../books/s" + e.CommandArgument.ToString() + ".cmk");
                fu.SaveAs(fn);
                SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["mainconectionstring"].ConnectionString);
                SqlCommand com = new SqlCommand();
                com.Connection = con;
                com.CommandText = "UPDATE BOOKS SET bok_hasdemo = 1, bok_updatedate=getDate() WHERE bok_id = @bokid";
                com.Parameters.Add(new SqlParameter("@bokid", Convert.ToInt32(e.CommandArgument)));
                con.Open();
                com.ExecuteNonQuery();
                con.Close();
            }
        }*/

        protected void RemoveSample(object sender, CommandEventArgs e)
        {
            string fn = Request.MapPath("../books/s" + e.CommandArgument.ToString() + ".cmk");
            SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["mainconectionstring"].ConnectionString);
            SqlCommand com = new SqlCommand();
            com.Connection = con;
            com.CommandText = "UPDATE BOOKS SET bok_hasdemo = 0, bok_updatedate=getDate() WHERE bok_id = @bokid";
            com.Parameters.Add(new SqlParameter("@bokid", Convert.ToInt32(e.CommandArgument)));
            con.Open();
            com.ExecuteNonQuery();
            con.Close();
            if (File.Exists(fn))
                File.Delete(fn);
        }

        protected void onInsertAuthor(object sender, CommandEventArgs e)
        {
            Label lbl = (Label)ListView1.EditItem.FindControl("Label1");
            ListBox lb = (ListBox)ListView1.EditItem.FindControl("ListBox1");
            int bokid = Convert.ToInt32(lbl.Text);
            SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["mainconectionstring"].ConnectionString);
            SqlCommand com = new SqlCommand();
            com.Connection = con;
            com.CommandText = "DECLARE @n int; SELECT @n = (SELECT COUNT(*) FROM BOOKS2AUTHORS WHERE a2b_bok_id = @a2b_bok_id AND a2b_aut_id = @a2b_aut_id); ";
            com.CommandText+= "IF @n>0 UPDATE BOOKS2AUTHORS SET a2b_deleted = 0, a2b_updatedate = getDate() WHERE a2b_bok_id = @a2b_bok_id AND a2b_aut_id = @a2b_aut_id ";
            com.CommandText += "ELSE INSERT BOOKS2AUTHORS (a2b_bok_id,a2b_aut_id,a2b_is_writter,a2b_is_designer,a2b_updatedate,a2b_deleted) VALUES (@a2b_bok_id,@a2b_aut_id,1,1,getDate(),0)";
            com.Parameters.Add(new SqlParameter("@a2b_bok_id", bokid));
            com.Parameters.Add(new SqlParameter("@a2b_aut_id", System.Data.SqlDbType.Int));
            con.Open();
            for (int i = 0; i < lb.Items.Count; i++)
            {
                if (lb.Items[i].Selected)
                {
                    com.Parameters["@a2b_aut_id"].Value = Convert.ToInt32(lb.Items[i].Value);
                    com.ExecuteNonQuery();
                }
            }
            con.Close();
            Response.Redirect(Request.RawUrl);
        }

        protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
        {
            if (e.Item.ItemType == ListViewItemType.DataItem)
            {
                ListViewDataItem lvdi = (ListViewDataItem)e.Item;                
                DataRowView drv = (DataRowView)lvdi.DataItem;

                DropDownList ddl = (DropDownList)e.Item.FindControl("tiers_list");
                if(ddl != null)
                SelectItem(ddl, (int)drv["bok_ptr_id"]);

            }
        }
    }
}
